#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <string>

using namespace std;

class TData
{
public:
    TData(const string &name, pthread_mutex_t* pmtx)
    :_name(name),_pmtx(pmtx)
    {}

public:
    string _name;
    pthread_mutex_t *_pmtx;
};

int tickets = 1000;
void* threadRoutine(void* args)
{
    int sum = 0;
    TData* td = static_cast<TData*>(args);
    //const char* name = static_cast<const char*>(args);
    while(true)
    {
        pthread_mutex_lock(td->_pmtx);
        if(tickets > 0)
        {
            usleep(2000);
            sum++;
            --tickets;
            pthread_mutex_unlock(td->_pmtx);
        }
        else
        {
            pthread_mutex_unlock(td->_pmtx);
            break;
        }
        usleep(2000);
    }

    pthread_mutex_lock(td->_pmtx);
    cout << "线程" << td->_name << "抢票完毕，最终抢到的票数 " << sum << endl;
    pthread_mutex_unlock(td->_pmtx);
    
    delete td;
    return nullptr;
}

int main()
{
    pthread_mutex_t mtx;

    pthread_mutex_init(&mtx, nullptr);

    pthread_t pt[5];
    for(int i = 0; i < 5; i++)
    {
        char* name = new char(16);
        snprintf(name, 16, "thread-%d", i);
        TData* td = new TData(name, &mtx);
        pthread_create(pt+i, nullptr,threadRoutine, td);
    }

    for(int i = 0; i < 5; i++)
    {
        pthread_join(pt[i],nullptr);
    }

    cout << "所有线程均已退出" << tickets << endl;

    pthread_mutex_destroy(&mtx);

    return 0;
}
